//
//  BaseItem.m
//  RainbowFM
//
//  Created by chenli on 14/12/29.
//  Copyright (c) 2014年 RB. All rights reserved.
//

#import "BaseItem.h"
#import <objc/runtime.h>

@implementation BaseItem

static const char *getPropertyType(objc_property_t property) {
    const char *attributes = property_getAttributes(property);
    char buffer[1 + strlen(attributes)];
    strcpy(buffer, attributes);
    char *state = buffer, *attribute;
    while ((attribute = strsep(&state, ",")) != NULL) {
        if (attribute[0] == 'T') {
            return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
        }
    }
    return "@";
}

-(instancetype)initWithAttributes:(NSDictionary *)attributes{
    self = [super init];
    if (self) {
        [self setAttributes:attributes];
    }
    
    return self;
}

-(SEL)getSetterSelWithAttibuteName:(NSString*)attributeName{
    NSString *capital = [[attributeName substringToIndex:1] uppercaseString];
    NSString *setterSelStr = [NSString stringWithFormat:@"set%@%@:",capital,[attributeName substringFromIndex:1]];
    return NSSelectorFromString(setterSelStr);
}

-(void)setAttributes:(NSDictionary*)dataDic{
    unsigned int outCount;
   objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    
    for (int i = 0; i<outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        
            SEL sel = [self getSetterSelWithAttibuteName:[NSString stringWithFormat:@"%s",propName]];
            if ([self respondsToSelector:sel]) {
                id dataDicValue = nil;
                if ([[dataDic objectForKey:[NSString stringWithFormat:@"%s",propName]] isKindOfClass:[NSArray class]] ||
                    [[dataDic objectForKey:[NSString stringWithFormat:@"%s",propName]] isKindOfClass:[NSDictionary class]]) {
                    dataDicValue = [dataDic objectForKey:[NSString stringWithFormat:@"%s",propName]];
                }
                else{
                    dataDicValue = [NSString stringWithFormat:@"%@",[dataDic objectForKey:[NSString stringWithFormat:@"%s",propName]]];
                }
                [self performSelectorOnMainThread:sel withObject:dataDicValue waitUntilDone:YES];

        }
    }
}

@end
